package com.briup.bookstore.service.impl;

import com.briup.bookstore.common.exception.CustomException;
import com.briup.bookstore.common.model.entity.User;
import com.briup.bookstore.common.model.param.PageParam;
import com.briup.bookstore.common.response.ResultCode;
import com.briup.bookstore.common.util.ObjectUtil;
import com.briup.bookstore.dao.UserDao;
import com.briup.bookstore.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

	private final UserDao userDao;

    @Override
    public PageInfo<User> pageQueryByClause(PageParam pageParam, User userParam) {
        /* 开始分页 */
        PageHelper.startPage(pageParam.pageNum(), pageParam.pageSize());
        /* 调用Dao层查询 */
        List<User> users = userDao.selectByClause(userParam);
        /* 封装为分页对象 */
        return PageInfo.of(users);
    }

	/**
	 * 添加用户
	 *
	 * @param userParam 用户添加的基础数据实体
	 */
	@Override
	public void add(User userParam) {
	    /* 参数校验 */
        if (ObjectUtil.anyNotHasText(
                userParam.getUsername(),
                userParam.getPassword())) {
            throw new CustomException(ResultCode.PARAM_NOT_COMPLETE);
        }

        /* 判断用户名是否已被使用 */
        if (ObjectUtil.nonNull(userDao.selectByUsername(userParam.getUsername()))) {
            throw new CustomException(ResultCode.USER_USERNAME_HAS_EXISTED);
        }

        /* 设置用户初始状态、注册时间等字段 */
        /* 将参数封装为Entity对象 */
        userParam.setRegisterTime(new Date())
                .setStatus(0)
                .setRoleId(2)
                .setVip(0);

        /* 调用Dao层执行插入 */
        userDao.insert(userParam);
    }

    @Override
    public void update(User userParam) {
        userDao.update(userParam);
    }

    @Override
    public User getById(Integer id) {
        return userDao.selectById(id);
    }

    @Override
    public void delete(List<Integer> ids) {
        userDao.delete(ids);
    }


}
